package com.shc.community.controller;

import com.shc.community.annotation.LoginRequired;
import com.shc.community.entity.ActivationConstant;
import com.shc.community.entity.LoginTicket;
import com.shc.community.entity.User;
import com.shc.community.service.FollowService;
import com.shc.community.service.LikeService;
import com.shc.community.service.UserService;
import com.shc.community.utils.CommunityUtil;
import com.shc.community.utils.CookieUtil;
import com.shc.community.utils.HostHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    private static final Logger lpgger = LoggerFactory.getLogger(UserController.class);

    @Value("${community.path.upload}")
    private String uploadPath;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private LikeService likeService;
    @Autowired
    private UserService userService;
    @Autowired
    private FollowService followService;
    @LoginRequired
    @RequestMapping(path = "/setting" , method = RequestMethod.GET)
    public String getSettingPage(){
        return "/site/setting";
    }
    @LoginRequired
    @RequestMapping(path = "/upload",method = RequestMethod.POST)
    private String uploadHeader(MultipartFile headerImage, Model model){
        //判断图片是否存在
        if (headerImage == null){
            model.addAttribute("error","您没有选择图片！");
            return "/site/setting";
        }
        //判断图片格式是否正确
        String filename = headerImage.getOriginalFilename();
        String suffix = filename.substring(filename.lastIndexOf("."));
        if (StringUtils.isBlank(suffix)){
            model.addAttribute("error","图片格式不正确！");
            return "/site/setting";
        }
        //生成随机图片文件名
        filename = CommunityUtil.generateUUID() + suffix;
        //确定文件存放位置
        File dest = new File(uploadPath + "/" + filename);
        try {
            //存储文件
            headerImage.transferTo(dest);
        } catch (IOException e) {
            lpgger.error("上传文件失败 ：" + e.getMessage());
            throw new RuntimeException("上传文件失败，服务器异常！",e);
        }
        //更新当前用户头像路径
        User user = hostHolder.getUser();
        String headerUrl = domain + contextPath + "/user/header/" + filename;
        userService.updateHeader(user.getId(),headerUrl);
        return "redirect:/index";
    }
    @RequestMapping(path = "/header/{fileName}",method = RequestMethod.GET)
    public void getHeader(@PathVariable("fileName") String fileName , HttpServletResponse response){
        //服务器存放路径
        fileName = uploadPath + "/" + fileName;
        //文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //响应图片
        response.setContentType("/image/" +suffix);
        try (
                ServletOutputStream outputStream = response.getOutputStream();
                FileInputStream inputStream = new FileInputStream(fileName);
             ) {
                byte[] buffer = new byte[1024];
                int b = 0;
                while ((b = inputStream.read(buffer)) != 1){
                    outputStream.write(buffer,0,b);
                 }
        } catch (IOException e) {
            lpgger.error("读取头像失败：" + e.getMessage());
        }
    }
    //修改用户密码
    @RequestMapping(path = "/password",method = RequestMethod.POST)
    public String updatePassword(String old_password ,String new_password,String confirm_password, Model model ,HttpServletRequest request){
        if (old_password == null){
            model.addAttribute("old_passwordMsg","密码不能为空！");
            return "/site/setting";
        }
        if (new_password == null){
            model.addAttribute("new_passwordMsg","密码不能为空！");
            return "/site/setting";
        }
        if (confirm_password == null){
            model.addAttribute("confirm_passwordMsg","密码不能为空！");
            return "/site/setting";
        }
        String ticket = CookieUtil.getVaule(request, "ticket");
        LoginTicket loginTicket = userService.findLoginTicket(ticket);
        User user = userService.findUserById(loginTicket.getUserId());
        old_password = CommunityUtil.md5(old_password + user.getSalt());
        if (!user.getPassword().equals(old_password)){
            model.addAttribute("old_passwordMsg","密码错误！");
            return "/site/setting";
        }
        if (!new_password.equals(confirm_password)){
            model.addAttribute("confirm_passwordMsg","两次输入的密码不一致！");
            return "site/setting";
        }
        userService.updatePassword(user.getId(), confirm_password);
        return "redirect:/index";
    }
    //个人主页
    @RequestMapping(path = "/profile/{userId}",method = RequestMethod.GET)
    public String getProfilePage(@PathVariable("userId") int userId,Model model){
        ActivationConstant constant = new ActivationConstant();
        User user = userService.findUserById(userId);
        if (user == null){
            throw new RuntimeException("该用户不存在！");
        }
        //用户
        model.addAttribute("user",user);
        //点赞数量
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount",likeCount);
        //查询关注的数量
        long followeeCount = followService.findFolloweeCount(userId, constant.getENTITY_TYPE_USER());
        model.addAttribute("followeeCount",followeeCount);
        //查询粉丝的数量
        long followerCount = followService.findFollowerCount(constant.getENTITY_TYPE_USER(), userId);
        model.addAttribute("followerCount",followerCount);
        //是否已关注
        boolean hasFollowed =false;
        if (hostHolder.getUser() != null){
            hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(), constant.getENTITY_TYPE_USER(), userId);
        }
        model.addAttribute("hasFollowed",hasFollowed);
        return "/site/profile";

    }
}
